<template>
    <div class="white-box-form">
        <el-form
            ref="ruleRef"
            :model="state.ruleForm"
            :rules="state.rules"
            label-width="120px"
            class="mt-20"
        >
            <el-form-item label="车辆负责人" prop="carHead">
                <el-input
                    v-model.trim="state.ruleForm.carHead"
                    clearable
                    placeholder="请输入车辆负责人"
                />
            </el-form-item>
            <el-form-item label="车牌号" prop="carNumber">
                <el-input
                    v-model.trim="state.ruleForm.carNumber"
                    clearable
                    placeholder="请输入车牌号"
                />
            </el-form-item>
            <el-form-item label="线路" prop="lineSid">
                <select-load-more
                    v-model:selectValue="state.ruleForm.lineSid"
                    v-model:options="state.lineOptions"
                    v-model:needFilterOptions="state.needFilterLineOptions"
                    value="sid"
                    label="lineName"
                    placeholder="请选择线路"
                    multiple
                    popper-class="line-select"
                    :apiFun="getLineOptions"
                />
            </el-form-item>
            <el-form-item label="归属网点" prop="outletsSid">
                <select-load-more
                    v-model:selectValue="state.ruleForm.outletsSid"
                    v-model:options="state.outletsOptions"
                    v-model:needFilterOptions="state.needFilterOutletsOptions"
                    value="sid"
                    label="outletsName"
                    placeholder="请选择归属网点"
                    popper-class="outlets-select"
                    :apiFun="getOutletsOptions"
                />
            </el-form-item>
            <el-form-item label="备注" prop="note">
                <el-input
                    v-model.trim="state.ruleForm.note"
                    type="textarea"
                    maxlength="100"
                    :autosize="{ minRows: 2 }"
                    clearable
                    show-word-limit
                    placeholder="请输入备注"
                />
            </el-form-item>

            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="state.ruleForm.status">
                    <el-radio
                        v-for="item in state.statusList"
                        :key="item.memberKey"
                        :value="item.memberKey"
                        >{{ item.memberName }}</el-radio
                    >
                </el-radio-group>
            </el-form-item>
        </el-form>

        <div class="foot-btn">
            <el-button
                type="primary"
                :loading="state.form_loading"
                @click="submitForm(ruleRef)"
            >
                {{ isEdit ? "修改" : "添加" }}
            </el-button>
        </div>
        <go-back />
    </div>
</template>

<script setup>
import { inject, ref, onMounted, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import GoBack from "@components/GoBack.vue";
import selectLoadMore from "@/components/selectLoadMore.vue";
import { getOutlets, getOutletDetail } from "@/apis/outlet/outlet.js";
import { getLines } from "@/apis/enterprise/line.js";
import {
    getCarDetail,
    addCar,
    editCar,
    getCarLines,
} from "@/apis/enterprise/car.js";
import { useDictStore } from "@stores/dict.js";

const dictStore = useDictStore();
dictStore.getDictMembers("data_status").then((res) => (state.statusList = res));

const router = useRouter();
const route = useRoute();

const $message = inject("$message");

const sid = route.query.sid;
const isEdit = ref(false);
const form_loading = ref(false);
const ruleRef = ref(null);
const state = reactive({
    statusList: [],
    ruleForm: {
        status: 0,
        lineSid: [],
        outletsSid: null,
        carHead: null,
        carNumber: null,
        note: null,
    },
    rules: {
        carHead: [
            { required: true, message: "请输入车辆负责人", trigger: "blur" },
        ],
        carNumber: [
            { required: true, message: "请输入车牌号", trigger: "blur" },
        ],
        lineSid: [{ required: true, message: "请选择线路", trigger: "blur" }],
        note: [{ required: true, message: "请输入备注", trigger: "blur" }],
        outletsSid: [
            { required: true, message: "请选择归属网点", trigger: "blur" },
        ],
    },
    outletsOptions: [], // 网点列表
    needFilterOutletsOptions: [], // 需要过滤的网点列表
    lineOptions: [], // 线路列表
    needFilterLineOptions: [], // 需要过滤的线路列表
});

onMounted(() => {
    if (/Edit$/.test(route.name)) {
        isEdit.value = true;
        getDetail();
    }
});

const getDetail = async () => {
    const res = await getCarDetail({ sid });
    if (res.data.code == 200) {
        state.ruleForm = res.data.data;
        getBindLines(state.ruleForm.sid);
        if (state.ruleForm.outletsSid) {
            getOutletsDetail(state.ruleForm.outletsSid).then((outlets) => {
                state.outletsOptions.push(outlets);
                state.needFilterOutletsOptions.push(outlets);
            });
        }
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 获取车辆绑定线路
const getBindLines = async (sid) => {
    const res = await getCarLines({ sid });
    if (res.data.code == 200) {
        // 数据回显，查询 option 添加到 options 中
        state.ruleForm.lineSid = [];

        res.data.data.forEach((item) => {
            state.ruleForm.lineSid.push(item.sid);
            state.lineOptions.push(item);
            state.needFilterLineOptions.push(item);
        });
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 分页获取线路
const getLineOptions = async (params) => {
    const res = await getLines({
        ...params,
        lineName: params.keyword,
    });
    if (res.data.code == 200) {
        return res;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 分页获取网点
const getOutletsOptions = async (params) => {
    const res = await getOutlets({
        ...params,
        outletsName: params.keyword,
    });
    if (res.data.code == 200) {
        return res;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 获取网点详情
const getOutletsDetail = async (sid) => {
    const res = await getOutletDetail({ sid });
    if (res.data.code == 200) {
        return res.data.data;
    } else {
        $message({ message: res.data.msg, type: "error" });
    }
};

// 提交表单
const submitForm = (formEl) => {
    if (!formEl) return;
    formEl.validate(async (valid, fields) => {
        if (valid) {
            form_loading.value = true;
            let res = null;
            if (isEdit.value) {
                res = await editCar(state.ruleForm);
            } else {
                res = await addCar(state.ruleForm);
            }
            form_loading.value = false;
            if (res.data.code == 200) {
                $message({
                    message: isEdit.value ? "修改成功" : "添加成功",
                    type: "success",
                });
                router.back();
            } else {
                $message({ message: res.data.msg, type: "error" });
            }
        }
    });
};
</script>
